package 分布式锁.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import 分布式锁.redis实现.EasyRedisDistributedLock;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @author hecai
 * @date 2021/5/25
 */
@RestController
public class RedisController {

    int count = 0;

    @GetMapping("/trylock")
    public String tryLock() throws InterruptedException {
//        String requestId = UUID.randomUUID().toString();
//        System.out.println(EasyRedisDistributedLock.tryGetDistributedLock("MyKey", requestId, 30));

        int clientcount = 100;
        CountDownLatch countDownLatch = new CountDownLatch(clientcount);
        ExecutorService executorService = Executors.newFixedThreadPool(clientcount);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            executorService.execute(() -> {
                //获取唯一ID字符串
                String requestId = UUID.randomUUID().toString();
                String key = "RedisLockKey";
                try {
                    // 循环尝试获取锁
                    while (!EasyRedisDistributedLock.tryGetDistributedLock(key, requestId, 30)) {
                        Thread.sleep(100);
                    }
                    count++;
                } catch (InterruptedException e) {
                    // 解锁
                    EasyRedisDistributedLock.releaseDistributedLock(key, requestId);
                }
                countDownLatch.countDown();
            });

        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.printf("执行线程数:{},总耗时:{},count数为:{}", clientcount, end - start, count);
        return "requestId";
    }


}
